import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:yyshort/common/model/useInfo_model.dart';
import 'package:yyshort/common/services/services.dart';
import 'package:yyshort/common/values/values.dart';
import 'package:get/get.dart';

class ConfigStore extends GetxController {
  static ConfigStore get to => Get.find();

  bool isFirstOpen = false;
  PackageInfo? _platform;
  String get version => _platform?.version ?? '-';
  bool get isRelease => bool.fromEnvironment("dart.vm.product");

  // 正确定义可观察的Locale变量
  // final Rxn<Locale> _locale = Rxn<Locale>(Locale('en', 'US'));
  final Rxn<Locale> _locale = Rxn<Locale>(Locale('en'));

  // 提供 getter 方法获取实际的Locale值（非Rx类型）
  Locale? get locale => _locale.value;

  List<Locale> languages = [
    Locale('en'),
    Locale('es'),
    // Locale('zh', 'Hans'),
    Locale('hant'),
    Locale('ja'),

    //     Locale('en', 'US'),
    // Locale('es', 'ES'),
    // // Locale('zh', 'Hans'),
    // Locale('zh', 'hant'),
    // Locale('ja', 'JP'),

    //英文：Locale('en', 'US')
    // 西班牙语：Locale('es', 'ES')
    // 日语：Locale('ja', 'JP')
    // 中文繁体：Locale('zh', 'Hant')
  ];

  @override
  void onInit() {
    super.onInit();
    isFirstOpen =
        StorageService.to.getBool(STORAGE_DEVICE_FIRST_OPEN_KEY) ?? true;
    _initLocale();
  }

  Future<void> getPlatform() async {
    _platform = await PackageInfo.fromPlatform();
  }

  Future<bool> saveAlreadyOpen() {
    return StorageService.to.setBool(STORAGE_DEVICE_FIRST_OPEN_KEY, false);
  }

  void _initLocale() {
    var langCode = StorageService.to.getString(STORAGE_LANGUAGE_CODE);
    var countryCode = StorageService.to.getString(STORAGE_COUNTRY_CODE);

    if (langCode.isNotEmpty && countryCode.isNotEmpty) {
      var targetLocale = Locale(langCode, countryCode);
      if (languages.contains(targetLocale)) {
        _locale.value = targetLocale;
        return;
      }
    }
    String temp = UserInfo().language;
    if (temp.isNotEmpty) {
      _locale.value = Locale(temp);
    } else {
      if (Get.deviceLocale != null) {
        var systemLocale = Get.deviceLocale!;
        var index = languages.indexWhere(
          (l) => l.scriptCode == systemLocale.scriptCode,
        );
        if (index != -1) {
          _locale.value = languages[index];
          return;
        }
      }

      _locale.value = Locale('en');
    }
  }

  void onUserInfoSettingUpdate(String languageCode) {
    var index = languages.indexWhere((l) => l.languageCode == languageCode);
    Locale locale;
    if (index != -1) {
      locale = languages[index];
      onLocaleUpdate(locale);
    }
  }

  void onLocaleUpdate(Locale value) {
    _locale.value = value; // 更新可观察变量
    Get.updateLocale(value);
    StorageService.to.setString(STORAGE_LANGUAGE_CODE, value.languageCode);
    StorageService.to.setString(STORAGE_COUNTRY_CODE, value.countryCode ?? '');
    update(); // 关键：通知所有依赖ConfigStore的组件重建
  }
}
